// 文件系统插件

string author = "Live";
string pluginName = "File 文件系统插件";
string version = "1.0";

// 当插件被初始化
void OnPluginInit()
{
    // 设置插件信息
    PluginData::SetAuthor(author);
    PluginData::SetName(pluginName);
    PluginData::SetVersion(version);

    // 提示
    ThePresident.InfoFeed("插件:"+pluginName+"| 版本:"+version+"| 作者:"+author,false);

    // 当玩家说
    Events::Player::PlayerSay.Hook( @PlayerSay );
}

HookReturnCode PlayerSay(CTerrorPlayer@ pPlayer, CASCommand@ pArgs){
	string arg = pArgs.Arg( 1 );
	string arg1 = "";
	string arg2 = "";

    // 切分字符串(这样就可以用空格传一个命令参数了)
	int subIndex = arg.findFirst(" ",0);
	if(not (subIndex < 0)){
		arg1 = arg.substr(0,subIndex);
		arg2 = arg.substr(subIndex+1,-1);
		//Chat.PrintToChat(all,""+arg1+"|"+arg2);
	}else{
		arg1 = arg;
	}

    if(arg1 == "!connect"){
        ConnectToDB();
    }
    if(arg1 == "!create"){
        create();
    }
    return HOOK_CONTINUE;

}

CSQLConnection@ gMainConnection;

void ConnectToDB()
{
    // SQL Connection info
    string strSQLHost = "localhost"; // Our hostname
    int iPort = 0; // if iPort is 0, then it will use default MySQL port
    string strSQLUser = "root"; // Our username
    string strSQLPass = "lingfeng"; // Our password
    string strSQLDB = "test"; // Our database

    // Create our connection
    SQL::Connect( strSQLHost, iPort, strSQLUser, strSQLPass, strSQLDB, OnSQLConnect );
}

void OnSQLConnect( CSQLConnection@ pConnection )
{
    // If our connection was a success, then we can save the CSQLConnection object to a local variable.
    // If not, stop here.
    if ( pConnection.Failed() ) return;

    // Apply our value
    @gMainConnection = pConnection;
    Chat.PrintToChat(all,"数据库连接成功");
}

void create(){
    if(gMainConnection is null)return;
    string sql = "CREATE TABLE IF NOT EXISTS `example_table` ("
            "`id` int(11) NOT NULL auto_increment,"
            "`authid` int(11) NOT NULL default '0',"
            "`health` int(11) NOT NULL default '0',"
            "`name` varchar(250)  NOT NULL default '',"
            "PRIMARY KEY  (`id`)"
        ");";
    SQL::SendAndIgnoreQuery( gMainConnection, sql );
}